package com.dycn.controller;

import com.dycn.dao.RedisDao;
import com.dycn.model.Activitys;
import com.dycn.model.CyUser;
import com.dycn.model.TasksActivitiesVo;
import com.dycn.service.ActivitysService;
import com.dycn.service.TaskService;
import com.dycn.service.WeixinService;
import com.dycn.util.AppResultData;
import com.dycn.util.CommGson;
import com.dycn.util.OkhttpUtil;
import com.dycn.util.UserConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("cyuser")
public class CyUserController {
    @Autowired
    TaskService taskService;

    @Autowired
    RedisDao redisDao;
    @Autowired
    WeixinService weixinService;

    @Autowired
    ActivitysService activitysService;

    @RequestMapping("signlist")
    public String list(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String code,Integer activityId) throws UnsupportedEncodingException {
        CyUser cyUser = getUser(httpServletRequest, httpServletResponse);
        if(cyUser==null&&code==null&&!UserConfigUtil.isDebug){
//           // return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaa974928147c87b9&redirect_uri=http%3a%2f%2fwx.sxbq998.cn/tasks/list&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            String url=OkhttpUtil.getInstance().getUrl(httpServletRequest);
            String realUrl=url+"cyuser/signlist?activityId="+activityId;
            model.addAttribute("url",URLEncoder.encode(realUrl,"utf-8"));
            return  "dzhd/wexinsign";}
        Map<String, Object> map = taskService.signList(cyUser, code,activityId, httpServletResponse);
        model.addAttribute("data",activitysService.selectByPrimaryKey(activityId).toActivitysVo());
        model.addAttribute("list", map);
        return "dzhd/qiandao";
    }

    @RequestMapping("zhuli")
    public String zhuli(Model model, String openId, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String code,Integer activityId) {
        CyUser cyUser = getUser(httpServletRequest, httpServletResponse);
        if(cyUser==null&&code==null&&!UserConfigUtil.isDebug){
//           // return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaa974928147c87b9&redirect_uri=http%3a%2f%2fwx.sxbq998.cn/tasks/list&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            if(openId!=null)
                model.addAttribute("openId",openId);
            model.addAttribute("activityId",activityId+"");
            return  "dzhd/wexinzhuli";
        }
        if (cyUser == null)
            cyUser = getCyUser(code, httpServletResponse);
//        if(openId==null)
//            return  "dzhd/zhuli?openId="+cyUser.getOpenid();

        // Map<String,Object> map = taskService.signList(cyUser,code,httpServletResponse);

        if (openId == null) {
            model.addAttribute("openid", cyUser.getOpenid());
            model.addAttribute("activityId",activityId+"");
            return "dzhd/zhulinouser";
        } else {
            int zhuliCount = taskService.zhuliCount(cyUser,4, openId,code,activityId,httpServletResponse);
            model.addAttribute("zhuliCount", zhuliCount + "");
            model.addAttribute("levzhuliCount", (3-zhuliCount) + "");
            model.addAttribute("openId",openId);
            Activitys activitys=activitysService.selectByPrimaryKey(activityId);
            model.addAttribute("data",activitys.toActivitysVo());
            return "dzhd/zhuli";
        }

    }



    @RequestMapping("sign")
    @ResponseBody
    public AppResultData sign(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String code,Integer activityId) {
        CyUser cyUser = getUser(httpServletRequest, httpServletResponse);
//        if(cyUser==null&&code==null)
////           // return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaa974928147c87b9&redirect_uri=http%3a%2f%2fwx.sxbq998.cn/tasks/list&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
////          return  "dzhd/wexin";
        return taskService.signUser(cyUser, code,activityId,httpServletResponse);

    }
    @RequestMapping("xuan")
    public String xuan(HttpServletRequest request,Model model,Integer activityId) {
        if(!UserConfigUtil.isDebug){
        Map<String,String> map=weixinService.wxConfig(request);
        model.addAttribute("data",map);
        }
        String num=redisDao.getValue("num"+activityId);
        if(num==null){
            num="1";
        }else {
            num=(Integer.parseInt(num)+1)+"";
        }
        redisDao.putForeverValue("num"+activityId,num);
        String share=redisDao.getValue("share"+activityId);
        if(share==null){
            share="0";
            redisDao.putForeverValue("share"+activityId,"0");
        }
        model.addAttribute("num",num+"");
        model.addAttribute("share",share+"");
        model.addAttribute("con",activitysService.selectByPrimaryKey(activityId).toActivitysVo());
        model.addAttribute("activityId",activityId);
        return  "dzhd/huodong";
    }
    @RequestMapping("addZhuanfa")
    @ResponseBody
    public  AppResultData addZhuanfa(Integer activityId){
        return  taskService.addZhuanfa(activityId);
    }

    private CyUser getUser(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Cookie[] cookies = httpServletRequest.getCookies();
        CyUser user = null;
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    String userString = redisDao.getValue(cookie.getValue());
                    cookie.setMaxAge(30 * 60 * 1000);
                    cookie.setPath("/");
                    httpServletResponse.addCookie(cookie);
                    redisDao.putSecondValue("user", cookie.getValue(), 30 * 60 * 1000);
                    user = CommGson.getInstance().toObject(userString, CyUser.class);
                }
            }
        }
        return user;
    }

    private CyUser getCyUser(String code, HttpServletResponse httpServletResponse) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
         String userString=OkhttpUtil.getInstance().getWeixinAccess(code);
         if(UserConfigUtil.isDebug)
         userString = "{\"openid\":\"o9XqEwoibgA2_D3fLBVQ7LV6h8uY1\",\"nickname\":\"呲尔不登睬等彩\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"太原\",\"province\":\"山西\",\"country\":\"中国\",\"headimgurl\":\"http:\\/\\/thirdwx.qlogo.cn\\/mmopen\\/vi_32\\/Q0j4TwGTfTKnibcf171MCFsR7JaYibBElK8wrol4ebFibrZWECZaRh81Eq8Ds8X3pMxY1U7OQsjsxN4yvDiaEVhTZg\\/132\",\"privilege\":[]}";
        userString = userString.replaceAll("\\[", "\"");
        userString = userString.replaceAll("]", "\"");
        redisDao.putSecondValue(uuid, userString, 30 * 60 * 1000);
        Cookie cookie = new Cookie("user", uuid);
        cookie.setMaxAge(30 * 60 * 1000);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
        return CommGson.getInstance().toObject(userString, CyUser.class);
    }
}
